#!/usr/bin/env python
#
#
#  Change	Date		Author			Description
# --------------------------------------------------------------------------------------------------------
#   001	        07-13-2013      Adam Dosch              Initial release
#   002         07-14-2013      Adam Dosch              Creating buildQueueQuery() function to build queue
#                                                       search pattern
#

import ConfigParser
import os
import sys

# PyMongo
try:
    from pymongo import errors as DatabaseErrors
    import pymongo
except ImportError:
    print "Install pymongo, please."

# RBS
try:
    from RBS import Config
    from system import Database
except ImportError:
    print "Update sys.path to load RBS modules, please."

def buildQueueQuery(ostypes, archtypes):
    # tcursor = queue.find( {'$or': [
    #                                  {'$and': [
    #                                             {'ostype': 'el7', 'arch': 'i386'}]
    #                                  },
    #                                  {'$and': [
    #                                             {'ostype': 'el6', 'arch': 'x86_64'}]
    #                                  }
    #                               ]
    #                        }
    #                      )

    if isinstance(ostypes, str):
        print "converting ostypes"
        ostypes = [ostypes]
    
    if isinstance(archtypes, str):
        print "converting archtypes"
        archtypes = [archtypes]

    or_list = []

    for ostype in ostypes:
        and_option = {'$and': []}
        
        for arch in archtypes:
            and_option = {'$and': [ {'ostype': ostype, 'arch': arch} ] }
            
            or_list.append(and_option)
    
    return {'$or': or_list}
    
def main():
    ostypes = configuration.getConfiguration('build')['ostypes']
    archtypes = configuration.getConfiguration('build')['archtypes']
    
    print "ostypes: ", ostypes
    print "archtypes: ", archtypes
    
    try:
        # Lets set up our database connection
        dbconn = Database.Connection("builder", server=configuration.getConfiguration('rbs')['dbserver'])
        print "Successfully connected to DB"
    except DatabaseErrors.ConnectionFailure, e:
        print "Problem connecting to database, dude: %s" % e
    
    # Establish connections to build and queue collections
    queue = dbconn.db['queue']


    #print queue.find({'ostype': types[0], 'ostype': types[1]}).count()
    
    q = buildQueueQuery(configuration.getConfiguration('build')['ostypes'], configuration.getConfiguration('build')['archtypes'])
    
    print queue.find(q).count()   

if __name__ == '__main__':
    # Look for config in these locations
    for f in ['/home/adosch/code/python/rbs','/tmp', '/etc/rbs', '/etc']:
        f += "/rbs-build.cfg"
        
        if os.path.isfile(f):
            if os.access(f, os.R_OK):
                
                global configuration
                configuration = Config(f)
                
                try:
                    configuration.loadConfiguration()
                    print "loading config"
                except:
                    raise "Error reading configuration file, dude!"
                
                break
    
    main()